#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>

int port_listening(int portno)
{
   int sockfd, newsockfd, clilen;
   char buffer[256];
   struct sockaddr_in serv_addr, cli_addr;
   int  n;
   
   /* First call to socket() function */
   sockfd = socket(AF_INET, SOCK_STREAM, 0);
   
   if (sockfd < 0) {
      perror("ERROR opening socket");
      return -1;
   }
   
   /* Initialize socket structure */
   bzero((char *) &serv_addr, sizeof(serv_addr));
   
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = INADDR_ANY;
   serv_addr.sin_port = htons(portno);
   
   /* Now bind the host address using bind() call.*/
   if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
      perror("ERROR on binding");
      return -1;
   }
      
   /* Now start listening for the clients, here process will
      * go in sleep mode and will wait for the incoming connection
   */
   
   listen(sockfd,5);
   clilen = sizeof(cli_addr);
   
   /* Accept actual connection from the client */
   newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
	
   if (newsockfd < 0) {
      perror("ERROR on accept");
      return -1;
   }
   
   /* If connection is established then start communicating */
   bzero(buffer,256);
   n = read( newsockfd,buffer,255 );
   
   if (n < 0) {
      perror("ERROR reading from socket");
      return -1;
   }
}

void dummy_calculation(int time_sleep)
{
    while (1)
    {
        unsigned int n = 100000000;
        unsigned int a = 1;
        unsigned int b = 1;
        for (unsigned int i = 0; i < n; i++)
        {
            unsigned int temp = a;
            a = b;
            b += temp;
            //printf("%d %d\n",a,b);
        }
        usleep(time_sleep);
    }
}

int is_prime(int num)
{
    if (num == 1 || num == 0)
        return 0;
    for (int i = 2; i < num; i++)
        if (num % i == 0)
            return 0;
    return 1;
}

void prime_generator(int time_sleep)
{
    while (1)
    {
        for (int i = 1; i < 9999; i++)
            //if (is_prime(i))
                //printf("%d\n",i);
            is_prime(i);
        usleep(time_sleep);
    }
}

int main(int argc, char *argv[])
{
    int time_sleep;
    int port;

    if (argc != 3) {
        fprintf(stderr,"usage: %s mode option\n", argv[0]);
        return -1;
    }
    if (!strcmp(argv[1], "port_listening")) {
        printf("mode: port listening\n");
        port = atoi(argv[2]);
        port_listening(port);
    } else if (!strcmp(argv[1], "calculation")) {
        printf("mode: calculation\n");
        time_sleep = atoi(argv[2]);
        dummy_calculation(time_sleep);
    }
    return 1;

}
